package gold.digger;

/**
 * Created by fanzhenyu02 on 2020/2/29.
 */
public class LC08 {
    public int myAtoi(String str) {
        str = escapeWhiteSpace(str);
        str = keepValidateNumber(str);
        if (null == str || str.length() == 0 || str.equals("+") || str.equals("-")) {
            return 0;
        }

        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
            return str.startsWith("-") ? Integer.MIN_VALUE : Integer.MAX_VALUE;
        }
    }

    private String escapeWhiteSpace(String str) {
        int startIndex = 0;
        for (; startIndex < str.length(); ++startIndex) {
            if (str.charAt(startIndex) == ' ') {
                continue;
            }

            return str.substring(startIndex);
        }

        return str.substring(startIndex);
    }

    private String keepValidateNumber(String str) {
        if (str.length() == 0) {
            return null;
        }

        if (str.charAt(0) != '+' && str.charAt(0) != '-' && (str.charAt(0) > '9' || str.charAt(0) < '0')) {
            return null;
        }

        int i = 1;
        for (; i < str.length(); ++i) {
            if (str.charAt(i) <= '9' && str.charAt(i) >= '0') {
                continue;
            }

            return str.substring(0, i);
        }

        return str.substring(0, i);
    }


    public static void main(String[] args) {
        LC08 an = new LC08();
        System.out.println(an.myAtoi("-91283472332"));
    }
}
